import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { STS } from 'ali-oss'
import { IOssConfig, ossRegToken } from '~/config/oss.config'

import { OSSCredentials } from '../interfaces/oss.interface'

@Injectable()
export class OssService {
  private readonly ossConfig: IOssConfig

  constructor(private readonly configService: ConfigService) {
    this.ossConfig = this.configService.get(ossRegToken)
  }

  /**
   * 获取OSS临时凭证
   * @returns OSS临时凭证
   */
  async getCredentials(): Promise<OSSCredentials> {
    const { accessKeyId, accessKeySecret, bucket, region, domain, arn } = this.ossConfig
    try {
      const sts = new STS({
        accessKeyId,
        accessKeySecret,
      })

      const result = await sts.assumeRole(
        arn, // role arn
        null, // policy
        60 * 60, // expiration
        'web-client', // session name
      )

      console.log(result)
      // 返回临时凭证
      return {
        accessKeyId: result.credentials.AccessKeyId,
        accessKeySecret: result.credentials.AccessKeySecret,
        securityToken: result.credentials.SecurityToken,
        expiration: result.credentials.Expiration,
        bucket,
        region,
        domain,
      }
    }
    catch (error) {
      throw new Error(`获取OSS临时凭证失败: ${error.message}`)
    }
  }
}
